package com.lwm.annotationandreflection.ref;

import com.lwm.entity.Employee;
import com.lwm.entity.Status;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author liweimin
 * @date 2020/9/25 11:39
 * @description
 */
public class ref08 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获得Class对象
        Class<?> aClass = Class.forName("com.lwm.entity.Employee");
        //构造一个对象
        /**
         * 本质调用无参构造器
         */
        Employee employee = (Employee) aClass.newInstance();
        //通过构造器创建对象
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class, int.class, double.class, Status.class);
        Employee lwm = (Employee) declaredConstructor.newInstance("lwm", 45, 45.3, Status.FREE);
        //通过反射获取一个方法
        Method setName = aClass.getDeclaredMethod("setName", String.class);
        setName.invoke(employee, "李二狗");
        System.out.println(employee.getName());
        Method getName = aClass.getDeclaredMethod("getName");
        System.out.println(getName.invoke(employee));
        Field name = aClass.getDeclaredField("name");
        //关闭程序安全检测
        name.setAccessible(true);
        name.set(employee, "了吗");
        System.out.println(getName.invoke(employee));

    }
}
